local CheckWidgetType = UI.CheckWidgetType
local CheckArgType = UI.CheckArgType
local CheckArgWidget = UI.CheckArgWidget
local MakeAccessor = UI.MakeAccessor
local MakeTypeSetter = UI.MakeTypeSetter

--[[ Texture @FIXME ]]--
local Texture = UI.NewWidgetType("Texture", "LayeredRegion")
Texture.parameters = {
	blend = "DISABLE",
	desaturated = false,
	texcoordleft = 0,
	texcoordright = 1,
	texcoordtop = 0,
	texcoordbottom = 1,
}

local ValidBlendMode = {
	DISABLE = true,
	BLEND = true,
	ALPHAKEY = true,
	ADD = true,
	MOD = true,
}

function Texture:Initialize(o)
	local t = UI.params[o]
	assert(t)
end

function Texture.prototype:GetTexture()
	CheckWidgetType("Texture:GetTexture", self, "Texture")
	local t = UI.params[self]
	return t.texture
end

function Texture.prototype:SetTexture(...)
	CheckWidgetType("Texture:SetTexture", self, "Texture")
	local t = UI.params[self]
	local c = select("#", ...)
	local tn = c >= 1 and type(...) or "nil"
	if c >= 1 and tn == "string" then
		t.texture = select(1, ...)
	elseif c >= 3 and tn == "number" then
		-- t.texture = "COLOR"
		local r, g, b, a = ...
		r = tonumber(r)
		g = tonumber(g)
		b = tonumber(b)
		a = tonumber(a or 1)
		t.texture = format("COLOR{%f,%f,%f,%f}", r, g, b, a)
	elseif tn == "nil" then
		t.texture = nil
	else
		error(string.format("Invalid parameters for Texture:SetTexture() (%d, %s)", c, tn))
	end
end

function Texture.prototype:SetBlendMode(mode)
	CheckWidgetType("Texture:SetBlendMode", self, "Texture")
	CheckArgType("Texture:SetBlendMode", 2, "mode", "string", mode)
	if not ValidBlendMode[mode] then
		error("Texture:SetBlendMode(), parameter 2 (mode) is an invalid blend mode name (%s)", tostring(mode))
	end
	UI.params[self].blend = mode
end

function Texture.prototype:SetDesaturated(d)
	CheckWidgetType("Texture:SetDesaturated", self, "Texture")
	local t = UI.params[self]

	t.desaturated = d and true or false
end

function api.global.SetPortraitTexture(texture, unit)
	if type(texture) == "string" then
		texture = api.global.getglobal(texture)
	end
	CheckArgWidget("SetPortraitTexture", 1, "texture", "Texture", texture)
	CheckArgType("SetPortraitTexture", 2, "unit", "string", unit)
	UI.params[texture].texture = "UNIT:"..unit
end

function api.global.SetPortraitToTexture(texture, icon)
	if type(texture) == "string" then
		texture = api.global.getglobal(texture)
	end
	CheckArgWidget("SetPortraitToTexture", 1, "texture", "Texture", texture)
	CheckArgType("SetPortraitToTexture", 2, "icon", "string", icon)
	UI.params[texture].texture = "ICON:"..icon
end

--~ MakeAccessor("Texture", "GetTextColor", {"textcolorred", "textcolorgreen", "textcolorblue", "textcoloralpha"})
MakeTypeSetter("Texture", "SetTexCoord", {"texcoordleft", "texcoordright", "texcoordtop", "texcoordbottom"}, {"number", "number", "number", "number"})
